package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConst;
import com.itheima.constant.RedisConst;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import com.itheima.untils.QiniuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.JedisPool;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/setmeal")
public class SetmealController {
    @Autowired
    JedisPool jedisPool;
    @RequestMapping("/upload")
    public Result upload(MultipartFile imgFile){

        String s = UUID.randomUUID().toString().replace("-", "");
        String originalFilename = imgFile.getOriginalFilename();
        String s1 = originalFilename.substring(originalFilename.lastIndexOf("."));
       String filename=s+s1;
        try {
            QiniuUtils.upload2Qiniu(imgFile.getBytes(),filename);
            jedisPool.getResource().sadd(RedisConst.SETMEAL_PIC_RESOURCES,filename);
            return new Result(true, MessageConst.PIC_UPLOAD_SUCCESS,filename);
        } catch (IOException e) {
            e.printStackTrace();
        return new Result(false,MessageConst.PIC_UPLOAD_FAIL);
        }


    }
    @Reference
    SetmealService setmealService;
    @RequestMapping("/add")
    public Result add(Integer[] checkgroupIds, @RequestBody Setmeal setmeal){
        try {
            setmealService.add(checkgroupIds,setmeal);
            return new Result(true,MessageConst.ADD_SETMEAL_SUCCESS);
        } catch (RuntimeException e) {
            e.printStackTrace();
            return new Result(false,e.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConst.ADD_SETMEAL_FAIL);
        }
    }
    @RequestMapping("/findpage")
    public PageResult findpage(@RequestBody QueryPageBean queryPageBean){
        PageResult pageResult=setmealService.findpage(queryPageBean);
        return pageResult;
    }
}
